/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.anjiplus.template.gaea.generator.modules.table.service;

import com.anjiplus.template.gaea.generator.config.GaeaGeneratorProperties;
import com.anjiplus.template.gaea.generator.modules.project.dao.entity.Project;
import com.anjiplus.template.gaea.generator.modules.project.service.ProjectService;
import com.anjiplus.template.gaea.generator.modules.table.dao.GeneratorTable;
import com.anjiplus.template.gaea.generator.modules.table.dao.GeneratorTableRepository;
import com.anjiplus.template.gaea.generator.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Zheng Jie
 * @date 2019-01-14
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TableServiceServiceImpl implements TableService {

    private final GeneratorTableRepository generatorTableRepository;

    @Autowired
    private GaeaGeneratorProperties gaeaGeneratorProperties;

    @Autowired
    private ProjectService projectService;

    @Override
    public GeneratorTable find(String schemaName, String tableName) {

        Map m = new HashMap();
        m.put("table_Name",tableName);
        m.put("schema_name",schemaName);
        List<GeneratorTable> generatorTables = generatorTableRepository.selectByMap(m);
        if(generatorTables == null || generatorTables.size() ==0){
            //代码生成 包路径默认配置，可以在页面修改
            String project = schemaName;
            String sub = project;
            if(project.contains("-")) {
                sub = project.replaceAll("-",".");
            }
            String t = StringUtils.toCamelCase(tableName);

            GeneratorTable cfg = new GeneratorTable(tableName);
            //cfg.setApiAlias("领域模型-功能说明");//手工维护
            cfg.setAuthor("dev-user");
            cfg.setPack("com.anjiplus.".concat(sub).concat(".business.modules.").concat(t));
            cfg.setPack(cfg.getPack().toLowerCase());
            cfg.setModuleName(project.concat("-business"));
            cfg.setProject(project);
            try {
                Project proj = projectService.selectOne("code", project);
                cfg.setProjectRoot(proj.getProjectRoot());
            }catch (Exception ignore){

            }
            cfg.setCover(false);
            cfg.setPath("/"+project.concat("-ui/src/views/").concat(t));
            cfg.setWorkspace(gaeaGeneratorProperties.getWorkspace());
            cfg.setPrefix("t_");
            this.initGenConfig(cfg);
            return cfg;
        }
        generatorTables.get(0).setWorkspace(gaeaGeneratorProperties.getWorkspace());
        return generatorTables.get(0);
    }

    @Override
    public GeneratorTable update(String schemaName, String tableName, GeneratorTable generatorTable) {
        generatorTable.setApiPath(generatorTable.getPath().substring(0, generatorTable.getPath().indexOf("src/")+3)+"/api/");
        LambdaQueryWrapper<GeneratorTable> w = Wrappers.lambdaQuery();
        w.eq(GeneratorTable::getTableName, tableName);
        w.eq(GeneratorTable::getSchemaName,schemaName);
        GeneratorTable c = generatorTableRepository.selectOne(w);
        if(c!=null) {
            generatorTable.setId(c.getId());
            generatorTableRepository.updateById(generatorTable);
        }else {
            generatorTableRepository.insert(generatorTable);
        }
        log.info("gen-template:{}",gaeaGeneratorProperties.getTemplatePath());
        return generatorTable;
    }
}
